import { getLocalHistories } from '@/utils/storage';
import { uniq } from 'lodash';
const initialState = {
  suggests: [] as string[],
  histories: uniq(getLocalHistories()),
  resultData: {} as ResultData,
};

export type ActionType =
  | { type: 'search/saveSuggests'; payload: string[] }
  | { type: 'search/saveHistories'; payload: string[] }
  | { type: 'search/clearHistories' }
  | { type: 'search/saveResults'; payload: ResultData }
  | { type: 'search/clearResults' };

const searchReducer = (state = initialState, action: ActionType): typeof initialState => {
  switch (action.type) {
    case 'search/saveSuggests':
      return {
        ...state,
        suggests: action.payload.filter((item) => !!item),
      };
    case 'search/saveHistories':
      return {
        ...state,
        histories: uniq(action.payload),
      };

    case 'search/clearHistories': {
      return {
        ...state,
        histories: [],
      };
    }

    case 'search/saveResults': {
      return {
        ...state,
        resultData: {
          ...action.payload,
          results: [...(state.resultData.results || []), ...action.payload.results],
        },
      };
    }

    case 'search/clearResults': {
      return {
        ...state,
        resultData: {} as ResultData,
      };
    }

    default:
      return state;
  }
};

export default searchReducer;

export interface ResultData {
  page: number;
  per_page: number;
  results: Result[];
  total_count: number;
}

export interface Result {
  art_id: string;
  title: string;
  aut_id: string;
  aut_name: string;
  comm_count: number;
  pubdate: string;
  cover: Cover;
  like_count: number;
  collect_count: number;
}

interface Cover {
  type: number;
  images?: string[];
}
